import { HashRouter } from "react-router-dom"
import Router from "@/routers/index"
import { getBrowserLang } from "@/utils/utils"
import { setLanguage } from "./redux/modules/global";
import { ConfigProvider } from 'antd';
import { useDispatch, useSelector } from "react-redux";
import zhCN from 'antd/locale/zh_CN';
import enUS from "antd/lib/locale/en_US";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import AuthRouter from "./routers/utils/authRouter";
import useTheme from "./styles/theme/useTheme";
import { State } from "./redux/interface";

const App = () => {
  const dispatch = useDispatch()
  const {assemblySize, language} = useSelector((state:State) => state.global)
  const [i18nLocale, setI18nLocale] = useState(zhCN)
  const { i18n } = useTranslation();
  const theme = useTheme()

  // 设置 antd 语言国际化
  const setAntdLanguage = () => {
    // 如果 redux 中有默认语言就设置成 redux 的默认语言，没有就设置成浏览器默认语言
    if(language && language == "zh") { 
      setI18nLocale(zhCN)
      return
    }
    if(language && language == "en") { 
      setI18nLocale(enUS)
      return
    }
    if(getBrowserLang() == "zh") { 
      setI18nLocale(zhCN)
      return
    }
    if(getBrowserLang() == "en") { 
      setI18nLocale(enUS)
      return
    }
  }

  useEffect(() => {
    // 全局使用国际化
    i18n.changeLanguage(language || getBrowserLang())
    dispatch(setLanguage(language || getBrowserLang()))
    setAntdLanguage()
  },[language])

  return (
    <HashRouter>
      <ConfigProvider 
        theme={theme}
        locale={i18nLocale} 
        componentSize={assemblySize}>
        <AuthRouter>
          <Router />
        </AuthRouter>
      </ConfigProvider>
    </HashRouter>
  )
}

export default App